package com.apps.MobileSms.Aliyun.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.apps.MobileSms.Aliyun.config.AliyunMobileSmsConfig;
import com.apps.MobileSms.Aliyun.enums.SmsConsts;
import com.apps.MobileSms.Aliyun.enums.SmsErrorCode;
import com.apps.MobileSms.Aliyun.enums.SmsTemplate;
import com.apps.MobileSms.Aliyun.helper.SendSmsHelper;
import com.apps.MobileSms.Aliyun.model.vo.SmsTemplateVO;
import com.apps.MobileSms.Aliyun.service.ISmsService;
import com.apps.sexctption.DataException;
import com.apps.sexctption.NullException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description: 短信SMS服务实现
 * @author: YuXD
 * @create: 2019-04-20 15:54
 **/
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {


    @Autowired
    private AliyunMobileSmsConfig smsConfig;

    @Autowired
    private SendSmsHelper sendSmsHelper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    //验证码的缓存前缀
    private final static String validCodePrifix="sms_code_";
    //验证码过期时间,5分钟
    private final static long validCodeExpire=300;

    @Override
    public void sendValidCodeSms(String mobile)
    {
        //生成一个随机的6位数验证码
        String code= RandomUtil.randomNumbers(6);
        Map<String,String> map=new HashMap<>();
        map.put("code",code);
        SmsTemplateVO smsTemplate=new SmsTemplateVO(SmsTemplate.COMMON_VERIFY_SMS.getTemplateCode(),mobile, map);
        sendSmsHelper.SendSms(smsTemplate);
        //发送成功则压入缓存
        redisTemplate.opsForValue().set(validCodePrifix+mobile,code,validCodeExpire);
    }

    @Override
    public void validMobileCode(String mobile, String code)
    {
        String validCode= (String) redisTemplate.opsForValue().get(validCodePrifix+mobile);
        if(null == validCode)
            throw new NullException("验证码已过期!");
        if(validCode.equals(code))
            throw new DataException("验证码错误");
        //删除验证码
        redisTemplate.delete(validCodePrifix+mobile);
    }

}
